package qq;

import java.awt.image.BufferedImage;
import java.io.BufferedReader;
import java.io.BufferedWriter;
import java.io.ByteArrayOutputStream;
import java.io.File;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.io.OutputStreamWriter;
import java.io.Serializable;
import java.io.UnsupportedEncodingException;
import java.net.HttpURLConnection;
import java.net.MalformedURLException;
import java.net.URL;
import java.net.URLEncoder;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.HashMap;
import java.util.Iterator;
import java.util.ListIterator;
import java.util.Map;
import java.util.Map.Entry;
import java.util.Random;
import java.util.Set;
import java.util.regex.Matcher;
import java.util.regex.Pattern;
import java.util.zip.GZIPInputStream;

import javax.imageio.ImageIO;

import atg.taglib.json.util.JSONArray;
import atg.taglib.json.util.JSONObject;
 /*ÀÏ°æÁ¬½ÓÀà (ÊÕÐÅÏ¢Ïß³Ì·ÅÔÚÁËÄÚ²¿ÀàÀï ½öÒ»¸öÏß³Ì)*/
@SuppressWarnings( { "unused", "deprecation" })
public class MiniQQClient implements Runnable {
	private String my_uid = "";

	private String qq = "158227642"; // 2586686564 //158227642

	private String password = "password"; // kk041kkstar //password

	private int clientid = 73937875;

	private String psessionid = "";

	private String ptwebqq;

	private String vfwebqq;

	private String skey;

	private final String host = "http://d.web2.qq.com";

	private String refer = this.host + "/proxy.html?v=20101025002";

	private String cookie = "";

	private Map<String, User> firends = new HashMap<String, User>();

	private Map<String, User> firends2 = new HashMap<String, User>();

	public enum METHOD {
		GET, POST
	}

	private boolean run = false;

	private PollMessageThread poll = new PollMessageThread();

	public Thread getPoolThread() {
		return poll;
	}

	public MiniQQClient(String qq, String password) {
		this.qq = qq;
		this.password = password;

		try {
			boolean login = login();
			if (login) {
				// fetchAllOnlineFriends();
				// fetchAllFriends();
				run = true;
				getPoolThread().start();
				log("QQ START SUCESS.......");

				// sendMsgToQQ("125671911", "¸çÉÏÏßÁË£¡");
			}
		} catch (Exception e) {
			e.printStackTrace();
			log("QQ·¢ÉúÒì³£ÍË³ö\t" + e.getMessage());
			Thread.currentThread().stop();
		}
	}

	public static void main(String[] args) {
		//
		Think.loadFile("c:/th.txt");
		Think.loadZangFile("c:/zang.txt");// 2644760340 kk041kkstar
		MiniQQClient clinet = new MiniQQClient("158227642", "password");
		try // 158227642 891020119
		{
			clinet.getPoolThread().join();
		} catch (Exception e) {
			System.out.println("QQÒì³£ÍË³ö\t" + e.getMessage());
		}
	}

	private boolean login() {
		// login 1
		String checkQQUrl = "http://ptlogin2.qq.com/check?appid=1003903&uin="
				+ qq;
		String result = sendHttpMessage(checkQQUrl, METHOD.GET.name(), null);
		Pattern p = Pattern.compile("\\,\\'([!\\w]+)\\'");
		Matcher m = p.matcher(result);
		String checkType = "";
		if (m.find()) {
			checkType = m.group(1);
		}
		String check = "";
		if (!checkType.startsWith("!")) {
			// Éú³ÉÍ¼Æ¬ÑéÖ¤Âë
			System.out.print("Éú³ÉÍ¼Æ¬ÑéÖ¤Âë ");
			// ÐèÒªÊäÈëÑéÖ¤Âë
			String getCheckImageUrl = "http://captcha.qq.com/getimage?aid=1003903&uin="
					+ qq + "&vc_type=" + checkType;
			String file = readCheckImage(getCheckImageUrl);
			log("Çë´ò¿ª" + file + "£¬²¢ÇÒÔÚÕâÀïÊäÈëÆäÖÐµÄ×Ö·û´®£¬È»ºó»Ø³µ£º");
			InputStreamReader ins = new InputStreamReader(System.in);
			BufferedReader br = new BufferedReader(ins);
			try {
				check = br.readLine();
			} catch (IOException e) {
				e.printStackTrace();
			}
		} else {
			check = checkType;
		}

		// login 2
		String loginUrl = "http://ptlogin2.qq.com/login?u="
				+ qq
				+ "&"
				+ "p="
				+ encodePass(this.password, check.trim())
				+ // /Ã÷ÏÔÑéÖ¤ÂëÐèÒªÇå³ý¿Õ¸ñ
				"&verifycode="
				+ check
				+ "&remember_uin=1&aid=1003903"
				+ "&u1=http%3A%2F%2Fweb2.qq.com%2Floginproxy.html%3Fstrong%3Dtrue"
				+ "&h=1&ptredirect=0&ptlang=2052&from_ui=1&pttype=1&dumy=&fp=loginerroralert";

		result = sendHttpMessage(loginUrl, METHOD.GET.name(), null);

		p = Pattern.compile("µÇÂ¼³É¹¦£¡");
		m = p.matcher(result);
		if (m.find()) {
			log("Welcome QQ : " + this.qq + " Login Success£¡");
		} else {
			log(checkType);
			return false;
		}

		// ´ÓcookieÖÐÌáÈ¡ptwebqq,skey
		p = Pattern.compile("ptwebqq=(\\w+);");
		m = p.matcher(cookie);
		if (m.find()) {
			this.ptwebqq = m.group(1);
		}
		p = Pattern.compile("skey=(@\\w+);");
		m = p.matcher(cookie);
		if (m.find()) {
			this.skey = m.group(1);
		}
		// log("ptwebqq="+ptwebqq+",skey="+skey);

		// login 3
		String channelLoginUrl = this.host + "/channel/login2";
		String content = "{\"status\":\"\",\"ptwebqq\":\"" + ptwebqq
				+ "\",\"passwd_sig\":\"\",\"clientid\":\"" + clientid + "\"}";
		try {
			content = URLEncoder.encode(content, "UTF-8");
		} catch (UnsupportedEncodingException e) {
		}
		content = "r=" + content;// postµÄÊý¾Ý
		result = sendHttpMessage(channelLoginUrl, METHOD.POST.name(), content);

		p = Pattern.compile("\"vfwebqq\":\"(\\w+)\"");
		m = p.matcher(result);
		if (m.find())
			this.vfwebqq = m.group(1);
		p = Pattern.compile("\"psessionid\":\"(\\w+)\"");
		m = p.matcher(result);
		if (m.find())
			psessionid = m.group(1);
		// log("vwebqq="+vfwebqq);
		// log("psessionid="+psessionid);

		return true;
	}

	/**
	 * ¶ÁÈ¡ÑéÖ¤Âë¡£·µ»ØÑéÖ¤ÂëÎÄ¼þ±£´æµÄÂ·¾¶
	 */
	private String readCheckImage(String url) {
		try {
			System.out.println("get>>>" + url);

			URL serverUrl = new URL(url);
			HttpURLConnection conn = (HttpURLConnection) serverUrl
					.openConnection();
			conn.setRequestMethod("GET");// "POST" ,"GET"

			conn.addRequestProperty("Accept-Charset", "UTF-8;");// GB2312,
			conn
					.addRequestProperty("User-Agent",
							"Mozilla/5.0 (Windows; U; Windows NT 5.1; zh-CN; rv:1.9.2.8) Firefox/3.6.8");
			conn.connect();
			// ·µ»ØµÄcookie
			if (conn.getHeaderFields().get("Set-Cookie") != null)
				for (String s : conn.getHeaderFields().get("Set-Cookie")) {
					cookie += s;
				}

			InputStream ins = conn.getInputStream();

			BufferedImage bi = ImageIO.read(ins);
			File f = new File("qqimg.jpg");
			ImageIO.write(bi, "jpg", f);

			return f.getAbsolutePath();
		} catch (Exception e) {
			e.printStackTrace();
		}
		return null;
	}

	// µÇÂ½³É¹¦ È¡QQºÃÓÑ
	public void fetchAllFriends() {
		String getFriendsurl = "http://s.web2.qq.com/api/get_user_friends2";
		// String getFriendsurl2 = "http://s.web2.qq.com/api/get_user_friends";
		String result = fetchAllFriends(getFriendsurl);
		// String result2 = fetchAllFriends(getFriendsurl2);
		// firends
		Map<String, User> user = getFriendInfo(result); //
		// Map<String, User> user2 = getFriendInfo(result2); // ÕæÕýµÄQQºÅÂë

		if (user != null) {
			Set<Map.Entry<String, User>> set = user.entrySet();
			for (Iterator<Entry<String, User>> it = set.iterator(); it
					.hasNext();) {
				Entry<String, User> e = it.next();
				User u = e.getValue();
				u.setQq(user.get(e.getKey()).getUin());
				log(u.getQq() + "\t" + u.getNick() + "\t" + u.getUin());
				firends.put(u.getQq(), u);
				firends2.put(u.getUin(), u);
			}
		}
	}

	// ÔÚÏßÓÃ»§
	public void fetchAllOnlineFriends() {
		String onlineUserURL = host + "/channel/get_online_buddies2";
		onlineUserURL = onlineUserURL + "?clientid=" + clientid
				+ "&psessionid=" + psessionid;
		String result = sendHttpMessage(onlineUserURL, METHOD.GET.name(), null);
		System.out.println(result);
	}

	@SuppressWarnings("unchecked")
	public Map<String, User> getFriendInfo(String result) {
		Map<String, User> users = new HashMap<String, User>(500);
		try {
			JSONObject retJson = new JSONObject(result);
			if (retJson.getInt("retcode") == 0) {
				JSONArray infos = retJson.getJSONObject("result").getJSONArray(
						"info");
				for (ListIterator<JSONObject> it = infos.listIterator(); it
						.hasNext();) {
					JSONObject obj = it.next();
					User user = new User(obj.getString("uin"), obj
							.getString("nick"), obj.getInt("face"), obj
							.getLong("flag"));
					users.put(user.getNick() + user.getFlag(), user);
				}
			}
		} catch (Exception e) {
			log("getFriendInfo failure  " + e.getMessage());
		}
		return users;
	}

	public String fetchAllFriends(String getFriendsurl) {
		// {"h":"hello","vfwebqq":"7fe84931db23dc5a0351d759905642bcf5d09632e001bbfc8822809067538431d4da9dd1e8e653a0"}
		String content = "{\"h\":\"hello\",\"vfwebqq\":\"" + vfwebqq + "\"}";
		try {
			content = URLEncoder.encode(content, "UTF-8");
			content = "r=" + content;
			String result = sendHttpMessage(getFriendsurl, METHOD.POST.name(),
					content);
			// log("AllFriends= "+result);
			return result;
		} catch (Exception e) {
			log("fetchAllFriends failure.............\t" + e.getMessage());
			return null;
		}
	}

	public User getFriend(String qq) {
		return this.firends.get(qq);
	}

	synchronized public boolean sendMsg(String toQQ, String message,
			String toGroup) {
		try {
			JSONObject json = new JSONObject();
			if (toGroup.length() > 0) {
				System.out.println("Ö´ÐÐµ½ÁËÕâÀï,ÈºÏûÏ¢");
				json.put("group_uin", toGroup);
			} else {
				json.put("to", toQQ);// Òª·¢ËÍµÄÈË
			}
			json.put("face", 330);

			JSONArray msg = new JSONArray();
			msg.add(message);
			JSONArray font = new JSONArray();
			font.add("font");

			JSONObject font1 = new JSONObject().put("name", "ËÎÌå").put("size",
					"10");

			JSONArray style = new JSONArray();
			style.add(0);
			style.add(0);
			style.add(0);
			font1.put("style", style);
			font1.put("color", "000000");

			font.add(font1);
			msg.add(font);

			json.put("content", msg.toString());
			json.put("msg_id", new Random().nextInt(10000000));
			json.put("clientid", this.clientid);
			json.put("psessionid", this.psessionid);// ÐèÒªÕâ¸ö²ÅÄÜ·¢ËÍ
			String sendMsgUrl = this.host + "/channel/send_msg2";
			String sendQunMsgUrl = this.host + "/channel/send_qun_msg2";
			String content = json.toString();

			try {
				content = URLEncoder.encode(content, "UTF-8");
			} catch (UnsupportedEncodingException e) {
			}// ËûÒªÐèÒª±àÂë
			content = "r=" + content;
			// ·¢ËÍ
			String res = null;

			if (toGroup.length() > 0)
				res = sendHttpMessage(sendQunMsgUrl, METHOD.POST.name(),
						content);
			else
				res = sendHttpMessage(sendMsgUrl, METHOD.POST.name(), content);

			// ²»³öÒâÍâ£¬ÕâÊÇ·µ»Ø½á¹û£º{"retcode":0,"result":"ok"}
			if (null == res || !res.contains("result"))
				return false;
			JSONObject rh = new JSONObject(res);
			if ("ok".equals(rh.getString("result"))) {
				return true;
			}
		} catch (Exception e) {
			log("send message to " + toQQ + " failure......\n" + e.getMessage());
		}
		return false;
	}

	public boolean sendMsgToQQ(String qq, String message) {
		return sendMsg(getFriend(qq).getUin(), message, "");
	}

	// HTTP ÏûÏ¢·¢ËÍ
	public String pollsendHttpMessage(String url, String method, String contents) {
		try {
			log("request=" + url);
			// ´úÀí
			// System.setProperty("proxySet", "true");
			// System.setProperty("proxyHost", "10.37.240.29");
			// System.setProperty("proxyPort", "8080");

			URL serverUrl = new URL(url);
			HttpURLConnection conn = (HttpURLConnection) serverUrl
					.openConnection();
			conn.setConnectTimeout(20000);
			conn.setRequestMethod(method);// "POST" ,"GET"
			if (null != refer)
				conn.addRequestProperty("Referer", refer);

			conn.addRequestProperty("Cookie", cookie);
			conn.addRequestProperty("Connection", "Keep-Alive");
			conn.addRequestProperty("Accept-Language", "zh-cn");
			conn.addRequestProperty("Accept-Encoding", "gzip, deflate");
			conn.addRequestProperty("Cache-Control", "no-cache");
			conn.addRequestProperty("Accept-Charset", "UTF-8;");
			conn
					.addRequestProperty(
							"User-Agent",
							"Mozilla/4.0 (compatible; MSIE 8.0; Windows NT 5.1; Trident/4.0; .NET CLR 2.0.50727)");
			if (method.equalsIgnoreCase(METHOD.GET.name())) {
				conn.connect();
			} else if (method.equalsIgnoreCase(METHOD.POST.name())) {

				conn.setDoOutput(true);
				conn.connect();
				conn.getOutputStream().write(contents.getBytes());
			} else
				throw new RuntimeException("your method is not implement");

			// log("conn.getHeaderFields()="+conn.getHeaderFields().toString());//ÏÔÊ¾ÏìÓ¦Í·

			if (conn.getHeaderFields().get("Location") != null) {// URL×Ô¶¯ÄÜ´¦ÀíÌø×ª£¬¹ÊÕâÀïÃ»ÓÐ×÷ÓÃ
				String location = conn.getHeaderFields().get("Location")
						.toString();
				log("ÓÐÌø×ªLocation=" + location);
				return location;
			}

			if (conn.getHeaderFields().get("Set-Cookie") != null) {
				for (String s : conn.getHeaderFields().get("Set-Cookie")) {
					cookie += s;
				}
			}

			InputStream ins = conn.getInputStream();

			// ´¦ÀíGZIPÑ¹ËõµÄ
			if (null != conn.getHeaderField("Content-Encoding")
					&& conn.getHeaderField("Content-Encoding").equals("gzip")) {
				byte[] b = null;
				GZIPInputStream gzip = new GZIPInputStream(ins);
				byte[] buf = new byte[1024 * 8];
				int num = -1;
				ByteArrayOutputStream baos = new ByteArrayOutputStream();
				while ((num = gzip.read(buf, 0, buf.length)) != -1) {
					baos.write(buf, 0, num);
				}
				b = baos.toByteArray();
				baos.flush();
				baos.close();
				gzip.close();
				ins.close();
				return new String(b).trim();
			}
			saveIns(ins);
			String charset = "UTF-8";
			InputStreamReader inr = new InputStreamReader(ins, charset);
			BufferedReader br = new BufferedReader(inr);

			String line = "";
			StringBuffer sb = new StringBuffer();
			do {
				sb.append(line);
				line = br.readLine();
			} while (line != null);
			log("response=" + sb);

			// notifyAll();////////////
			return sb.toString();
		} catch (MalformedURLException e) {
			e.printStackTrace();
			return null;
		} catch (IOException e) {
			e.printStackTrace();
			return null;
		}

	}

	public String sendHttpMessage(String url, String method, String contents) {
		try {
			log("request=" + url);
			// ´úÀí
			// System.setProperty("proxySet", "true");
			// System.setProperty("proxyHost", "10.37.240.29");
			// System.setProperty("proxyPort", "8080");

			URL serverUrl = new URL(url);
			HttpURLConnection conn = (HttpURLConnection) serverUrl
					.openConnection();
			conn.setConnectTimeout(20000);
			conn.setRequestMethod(method);// "POST" ,"GET"
			if (null != refer)
				conn.addRequestProperty("Referer", refer);

			conn.addRequestProperty("Cookie", cookie);
			conn.addRequestProperty("Connection", "Keep-Alive");
			conn.addRequestProperty("Accept-Language", "zh-cn");
			conn.addRequestProperty("Accept-Encoding", "gzip, deflate");
			conn.addRequestProperty("Cache-Control", "no-cache");
			conn.addRequestProperty("Accept-Charset", "UTF-8;");
			conn
					.addRequestProperty(
							"User-Agent",
							"Mozilla/4.0 (compatible; MSIE 8.0; Windows NT 5.1; Trident/4.0; .NET CLR 2.0.50727)");
			if (method.equalsIgnoreCase(METHOD.GET.name())) {
				conn.connect();
			} else if (method.equalsIgnoreCase(METHOD.POST.name())) {

				conn.setDoOutput(true);
				conn.connect();
				conn.getOutputStream().write(contents.getBytes());
			} else
				throw new RuntimeException("your method is not implement");

			// log("conn.getHeaderFields()="+conn.getHeaderFields().toString());//ÏÔÊ¾ÏìÓ¦Í·

			if (conn.getHeaderFields().get("Location") != null) {// URL×Ô¶¯ÄÜ´¦ÀíÌø×ª£¬¹ÊÕâÀïÃ»ÓÐ×÷ÓÃ
				String location = conn.getHeaderFields().get("Location")
						.toString();
				log("ÓÐÌø×ªLocation=" + location);
				return location;
			}

			if (conn.getHeaderFields().get("Set-Cookie") != null) {
				for (String s : conn.getHeaderFields().get("Set-Cookie")) {
					cookie += s;
				}
			}

			InputStream ins = conn.getInputStream();

			// ´¦ÀíGZIPÑ¹ËõµÄ
			if (null != conn.getHeaderField("Content-Encoding")
					&& conn.getHeaderField("Content-Encoding").equals("gzip")) {
				byte[] b = null;
				GZIPInputStream gzip = new GZIPInputStream(ins);
				byte[] buf = new byte[1024 * 8];
				int num = -1;
				ByteArrayOutputStream baos = new ByteArrayOutputStream();
				while ((num = gzip.read(buf, 0, buf.length)) != -1) {
					baos.write(buf, 0, num);
				}
				b = baos.toByteArray();
				baos.flush();
				baos.close();
				gzip.close();
				ins.close();
				return new String(b).trim();
			}

			// saveIns(ins);

			String charset = "UTF-8";
			InputStreamReader inr = new InputStreamReader(ins, charset);
			BufferedReader br = new BufferedReader(inr);

			String line = "";
			StringBuffer sb = new StringBuffer();
			do {
				sb.append(line);
				line = br.readLine();
			} while (line != null);
			log("response=" + sb);

			// notifyAll();////////////
			return sb.toString();
		} catch (MalformedURLException e) {
			e.printStackTrace();
			return null;
		} catch (IOException e) {
			e.printStackTrace();
			return null;
		}

	}

	private InputStream Ins = null;

	private void saveIns(InputStream ins) {
		Ins = ins;
	}

	public InputStream getIns() {
		log("Ins!=null->" + (Ins != null));

		return Ins;
	}

	// ¼ÓÃÜÃÜÂë
	public String encodePass(String pass, String code) {
		try {
			MD5 md = new MD5();
			String t = md.calcMD5(md.calcMD5_3(pass) + code);
			return t.toString();
		} catch (Exception e) {
			e.printStackTrace();
		}
		return null;
	}

	// ¼ÇÂ¼ÈÕÖ¾
	private void log(String msg) {
		System.out.println(new SimpleDateFormat("yyyy-MM-dd hh:mm:ss")
				.format(new Date())
				+ " : " + msg);
	}

	public String numToIp(Long num) {
		String aaa = Long.toHexString(num);
		String n1 = Integer.parseInt(aaa.substring(0, 2), 16) + "";
		String n2 = Integer.parseInt(aaa.substring(2, 4), 16) + "";
		String n3 = Integer.parseInt(aaa.substring(4, 6), 16) + "";
		String n4 = Integer.parseInt(aaa.substring(6), 16) + "";

		return n1 + "." + n2 + "." + n3 + "." + n4;
	}

	HashMap<String, Think> ThinkRobot = new HashMap<String, Think>();

	public void receiveMsg(JSONObject value, boolean isGroup) throws Exception {
		if (!isGroup) {
			String content = value.getJSONArray("content").getString(1);
			String from_uin = value.getString("from_uin");
			String reply_ip = value.getString("reply_ip");

			String thw = null;

			if (ThinkRobot.containsKey(from_uin))
				thw = ThinkRobot.get(from_uin).getWords(content);
			else {
				ThinkRobot.put(from_uin, new Think(content, from_uin, this,
						isGroup));
				thw = ThinkRobot.get(from_uin).getWords(content);
			}

			if (thw.length() == 0)
				return;
			if ("911".equals(thw))
				return;// thw = "";//ÎÒ²»ÖªµÀÔõÃ´»Ø´ð£¬Äã½ÌÎÒºÃÂð£¿\nÊ¹ÓÃÒÔÏÂ¸ñÊ½½ÌÎÒ:\nteach:ÎÊÌâ:´ð°¸
			if (sendMsg(from_uin + "", thw, ""))
				log("·¢ËÍ³É¹¦");

			System.out.print(from_uin + "Ëµ£º\n" + content + "\n\n»úÆ÷ÈË»Ø´ðËµ£º\n"
					+ thw);

			Thread.sleep(500);
		} else {
			String content = value.getJSONArray("content").getString(1);
			String group_uin = value.getString("from_uin");
			String reply_ip = value.getString("reply_ip");

			String thw = null;

			if (ThinkRobot.containsKey(group_uin))
				thw = ThinkRobot.get(group_uin).getWords(content);
			else {
				ThinkRobot.put(group_uin, new Think(content, group_uin, this,
						isGroup));
				thw = ThinkRobot.get(group_uin).getWords(content);
			}

			if (thw.length() == 0)
				return;
			if (!"911".equals(thw))
				if (thw.length() > 95) {
					thw = thw.substring(0, 95)
							+ "......\nÏëÖªµÀ¸ü¶àÐÅÏ¢?Äú¿ÉÒÔÏÈ¼ÓÎÒºÃÓÑÔÙË½ÁÄÎÊÎÒÅ¶£¡";// "²»ºÃÒâË¼Å¶£¬Äú²éµÄÄÚÈÝÓÐµã¶à£¬ÎªÁË²»´òÈÅÆäËûÓÃ»§£¬Äú¿ÉÒÔÏÈ¼ÓÎÒºÃÓÑÔÙË½ÁÄÎÊÎÒÅ¶£¡";

					if (sendMsg("", thw, group_uin))
						log("·¢ËÍ³É¹¦");
				} else if (sendMsg("", thw, group_uin))
					log("·¢ËÍ³É¹¦");

			System.out.print(group_uin + "Ëµ£º\n" + content + "\n\n»úÆ÷ÈË»Ø´ðËµ£º\n"
					+ thw);

			Thread.sleep(500);
		}
	}

	public void changeStatus(JSONObject value) throws Exception {
		long from_uin = value.getLong("uin");
		String status = value.getString("status");
		// User u = firends2.get(from_uin);
		log("ÓÃ»§£º"/* + u.getNick() */+ "\t" + status);

	}

	class PollMessageThread extends Thread {
		public Map<String, String> dic = new HashMap<String, String>();

		public void saveFile(final String path) {
			new Thread() {
				public void run() {
					BufferedWriter bw = null;
					try {
						bw = new BufferedWriter(new OutputStreamWriter(
								new FileOutputStream(path)));
					} catch (FileNotFoundException e1) {
						e1.printStackTrace();
					}
					Object[] dk = dic.keySet().toArray();
					Object[] dv = dic.values().toArray();
					for (int i = 0; i < dic.size(); i++) {
						try {
							// bw.write(dk[i] + "#" + dv[i]+"&");
							bw.write(dv[i] + "  &  ");
						} catch (IOException e) {
							e.printStackTrace();
						}
					}
					try {
						bw.flush();
					} catch (IOException e) {
						e.printStackTrace();
					}
					try {
						bw.close();
					} catch (IOException e) {
						e.printStackTrace();
					}
				}
			}.start();
		}

		public void run() {
			String pollUrl = host + "/channel/poll2?clientid=" + clientid
					+ "&psessionid=" + psessionid;
			while (run) {
				try {
					String ret = pollsendHttpMessage(pollUrl,
							METHOD.GET.name(), null);
					JSONObject retJ = new JSONObject(ret);
					int retcode = retJ.getInt("retcode");
					if (retcode == 0) {
						JSONArray result = retJ.getJSONArray("result");
						String poll_type = result.getJSONObject(0).getString(
								"poll_type");
						JSONObject value = result.getJSONObject(0)
								.getJSONObject("value");
						if ("message".equals(poll_type)) {// ºÃÓÑÏûÏ¢
							JSONArray content_type = null;
							try {
								content_type = value.getJSONArray("content")
										.getJSONArray(1);// Èç¹û·ÇÍ¼Æ¬,½«±¨´í
								if ("cface".equals(content_type.getString(0))) {// ·Ç±íÇéÍ¼Æ¬
									log("·Ç±íÇéÍ¼Æ¬");
									String lcid = value.getString("msg_id");
									String guid = content_type.getString(1);
									String to = value.getString("from_uin");
									String get_cface2 = "http://d.web2.qq.com/channel/get_cface2?lcid="
											+ lcid
											+ "&guid="
											+ guid
											+ "&to="
											+ to
											+ "&count=5&time=1&clientid="
											+ clientid
											+ "&psessionid="
											+ psessionid;

									String cface_url = pollsendHttpMessage(
											get_cface2, METHOD.GET.name(), null);

									BufferedImage bi = ImageIO.read(Ins);
									File f = new File("img.jpg");
									ImageIO.write(bi, "jpg", f);
									log("f.getAbsolutePath()"
											+ f.getAbsolutePath());
									// String pick_url =
									// sendHttpMessage("http://stu.baidu.com/i?rt=0&rn=10&ct=0&tn=baiduimagepc&ftn=indeximage",
									// METHOD.POST.name(), cface_url);
									// log("cface_url="+ cface_url);
									// log("pick_url="+ pick_url);
									continue;
								}

								if ("face".equals(content_type.getString(0))) {// ±íÇéÍ¼Æ¬
									log("±íÇéÍ¼Æ¬");// Èç¹û·¢ÎÄ×ÖºÍÍ¼Æ¬¹²´æµÄÇé¿öÊ±£¬ÉÏÃæµÄÅÐ¶Ï½«²»ÕýÈ·,ÐèÒªÍ³³ïÅÐ¶ÏÅÐ¶Ï
									int face_id = content_type.getInt(1);
									String content = value.getJSONArray(
											"content").getString(1);
									dic.put(content, String.valueOf(face_id));
									// saveFile("c:/cface.txt");
									log("±íÇé±àºÅÎª" + face_id);
									continue;
								}
							} catch (Exception e) {
								log("·ÇÍ¼Æ¬ÐÅÏ¢ " + e);
								e.printStackTrace();
							}

							receiveMsg(value, false);

						} else if ("buddies_status_change".equals(poll_type)) {// ºÃÓÑÉÏÏÂÏß
							changeStatus(value);
						} else if ("group_message".equals(poll_type)) {// ÈºÏûÏ¢
							log("ÈºÏûÏ¢value=" + value);
							JSONArray content_type = null;
							try {
								content_type = value.getJSONArray("content")
										.getJSONArray(1);
								if ("cface".equals(content_type.getString(0))) {// ·Ç±íÇéÍ¼Æ¬
									log("·Ç±íÇéÍ¼Æ¬");
									/*
									 * String lcid = value.getString("msg_id");
									 * String guid = content_type.getString(1);
									 * String to = value.getString("from_uin");
									 * String get_cface2 =
									 * "http://d.web2.qq.com/channel/get_cface2?lcid="
									 * +lcid+"&guid="+guid+"&to="+to+
									 * "&count=5&time=1&clientid="
									 * +clientid+"&psessionid="+psessionid;
									 * 
									 * String cface_url =
									 * sendHttpMessage(get_cface2,
									 * METHOD.GET.name(), null);
									 * 
									 * BufferedImage bi = ImageIO.read(Ins);
									 * File f =new File("img.jpg");
									 * ImageIO.write(bi, "jpg", f);
									 * log("f.getAbsolutePath()"
									 * +f.getAbsolutePath()); //String pick_url =
									 * sendHttpMessage(
									 * "http://stu.baidu.com/i?rt=0&rn=10&ct=0&tn=baiduimagepc&ftn=indeximage" ,
									 * METHOD.POST.name(), cface_url);
									 * //log("cface_url="+ cface_url);
									 * //log("pick_url="+ pick_url);
									 */continue;
								}
								if ("face".equals(content_type.getString(0))) {// ±íÇéÍ¼Æ¬
									log("±íÇéÍ¼Æ¬");// Èç¹û·¢ÎÄ×ÖºÍÍ¼Æ¬¹²´æµÄÇé¿öÊ±£¬ÉÏÃæµÄÅÐ¶Ï½«²»ÕýÈ·,ÐèÒªÍ³³ïÅÐ¶ÏÅÐ¶Ï
									/*
									 * int face_id = content_type.getInt(1);
									 * String content =
									 * value.getJSONArray("content"
									 * ).getString(1); dic.put(content,
									 * String.valueOf(face_id));
									 * saveFile("c:/cface.txt");
									 * log("±íÇé±àºÅÎª"+face_id); switch(face_id){
									 * case 1:
									 * 
									 * break; }
									 */
									continue;
								}
							} catch (Exception e) {

							}

							receiveMsg(value, true);

						}
						// system_message ÊÇÏµÍ³ÏûÏ¢
					} else if (retcode == 121) {
						run = false;
						log("QQÒÑ¾­ÔÚ±ð´¦µÇÂ¼£¡");
					}
					Thread.sleep(1000);
				} catch (Exception e) {
					e.printStackTrace();
					log("Response PollMessage failure = " + e.getMessage());
				}
			}
		}
	}

	public void run() {
		// TODO ×Ô¶¯Éú³É·½·¨´æ¸ù

	}

}

@SuppressWarnings("serial")
class User implements Serializable {
	private String uin;

	private String qq;

	private String nick;

	private int face;

	private long flag;

	public User() {
		super();
	}

	public User(String uin, String nick, int face, long flag) {
		super();
		this.uin = uin;
		this.nick = nick;
		this.face = face;
		this.flag = flag;
	}

	public String getUin() {
		return uin;
	}

	public void setUin(String uin) {
		this.uin = uin;
	}

	public String getQq() {
		return qq;
	}

	public void setQq(String qq) {
		this.qq = qq;
	}

	public String getNick() {
		return nick;
	}

	public void setNick(String nick) {
		this.nick = nick;
	}

	public int getFace() {
		return face;
	}

	public void setFace(int face) {
		this.face = face;
	}

	public long getFlag() {
		return flag;
	}

	public void setFlag(long flag) {
		this.flag = flag;
	}

	@Override
	public String toString() {
		String user = this.uin + "\t\t" + this.qq + "\t\t" + this.nick + "\t\t"
				+ this.flag;
		return user;
	}
}
